package com.hcl.security.handle;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.hcl.security.config.username.UsernameForm;
import com.hcl.security.domain.LoginUser;
import com.hcl.security.utils.JsonUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import com.hcl.security.utils.JwtUtil;
import com.hcl.security.utils.Result;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * 登录成功处理器
 */
public class LoginAuthenticationSuccessHandler
		implements AuthenticationSuccessHandler {
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication authentication)
			throws IOException {
		// 根据authentication生成token
		LoginUser principal = (LoginUser) authentication.getPrincipal();
		Map<String, Object> map = new HashMap<>();
		map.put("username", principal.getUsername());
		map.put("password", principal.getPassword());
		JwtUtil.generateToken(map, principal.getUsername());
		response.setContentType("application/json;charset=utf-8");
		response.getWriter().println(JsonUtils.objectToJson(Result
				.ok(JwtUtil.generateToken(map, principal.getUsername()))));
		response.getWriter().flush();
		response.getWriter().close();
	}
}
